package com.spring.pick2pick;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.spring.pick2pick.common.PageHandler;
import com.spring.pick2pick.common.Util;
import com.spring.pick2pick.dao.AdminDao;
import com.spring.pick2pick.model.AdminItem;

@Controller
public class AdminController {
	
	@Autowired
	AdminDao adminDao;
	
	//private static final Logger logger = LoggerFactory.getLogger(AdminController.class);
	
	/** 관리자 리스트 목록 */
	@RequestMapping(value = "listAdmin", method = RequestMethod.GET)
	public String listAdmin(Locale locale, Model model, HttpServletRequest request) {
		int page = 1;
		int size = 10;
		String pageStr = request.getParameter("page");
		
		if (pageStr != null) {
			page = Integer.parseInt(pageStr);
		}
		
		model.addAttribute("list", adminDao.getAdminList(page, size));
		model.addAttribute("page", PageHandler.getInstance());
		
		return "admin/listAdmin";
	}
	
	/** 관리자 계정 추가 */
	@RequestMapping(value = "addAdmin", method = RequestMethod.GET)
	public String addAdmin(Locale locale, Model model) {
		return "admin/addAdmin";
	}
	
	/** 관리자계정 추가후 리스트 목록 */
	@RequestMapping(value = "addAdminOk", method = RequestMethod.POST)
	public String addAdminOk(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		String nickName = request.getParameter("nickName");
		nickName = nickName.replace("&", "&amp;");
		nickName = nickName.replace("<", "&lt;");
		nickName = nickName.replace(">", "&gt;");
		
		String adminId = request.getParameter("adminId");
		String passWord1 = request.getParameter("passWord1");
		String adminLevelStr = request.getParameter("adminLevel");
		
		if (nickName == null || adminId == null || passWord1 == null || adminLevelStr == null ||
				nickName.equals("") || adminId.equals("") || passWord1.equals("") || adminLevelStr.equals("")) {
			Util.getInstance().alertPage("필수입력 항목이 누락되었습니다.", response);
		} else {
			int adminLevel = Integer.parseInt(adminLevelStr);
			AdminItem item = new AdminItem();
			item.setNickName(nickName);
			item.setAdminId(adminId);
			item.setAdminPw(passWord1);
			item.setAdminLevel(adminLevel);
			
			int result = adminDao.addAdmin(item);
			
			if (result > 0) {
				try {
					response.sendRedirect("listAdmin");
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				Util.getInstance().alertPage("추가에 실패하였습니다.", response);
				
			}
		}
		return null;
	}
	
	/** 관리자 활성여부 변경 */
	@RequestMapping(value = "activityAdmin", method = RequestMethod.GET)
	public String activityAdmin(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		String pageStr = request.getParameter("page");
		String idStr = request.getParameter("id");
		String isActivityStr = request.getParameter("isActivity");
		
		if (pageStr == null || idStr == null || isActivityStr == null || pageStr.equals("") || idStr.equals("") || isActivityStr.equals("")) {
			Util.getInstance().alertPage("필수입력 항목이 누락되었습니다.", response);
		} else {
			int page = Integer.parseInt(pageStr);
			int id = Integer.parseInt(idStr);
			int isActivity = Integer.parseInt(isActivityStr);
			
			if (isActivity == 0) {
				isActivity = 1;
			} else if (isActivity == 1) {
				isActivity = 0;
			}
			
			AdminItem item = new AdminItem();
			item.setIdAdmin(id);
			item.setIsActivity(isActivity);
			int result = adminDao.editActivity(item);
			
			if (result > 0) {
				
				String html = "<!doctype html>";
				html += "<head>";
				html += "<meta charset='utf-8'>";
				html += "<script>";
				html += "alert('정상적으로 수정되었습니다.');";
				html += "location.replace('listAdmin?page=" + page + "');";
				html += "</script>";
				html += "</head>";
				html += "</html>";
				
				try {
					response.setCharacterEncoding("utf-8");
					PrintWriter out = response.getWriter();
					out.print(html);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				Util.getInstance().alertPage("활성여부 수정에 실패하였습니다.", response);
			}
			
		}
		
		return null;
	}
	
	/** 관리자 계정 삭제 */
	@RequestMapping(value = "deleteAdminOk", method = RequestMethod.POST)
	public String deleteAdminOk(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		String pageStr = request.getParameter("page");
		String idStr = request.getParameter("idAdmin");
		
		if (pageStr == null || idStr == null || pageStr.equals("") || idStr.equals("")) {
			Util.getInstance().alertPage("필수입력 항목이 누락되었습니다.", response);
		} else {
			int page = Integer.parseInt(pageStr);
			int id = Integer.parseInt(idStr);
			
			AdminItem item = new AdminItem();
			item.setIdAdmin(id);
			int result = adminDao.deleteAdmin(item);
			
			if (result > 0) {
				
				String html = "<!doctype html>";
				html += "<head>";
				html += "<meta charset='utf-8'>";
				html += "<script>";
				html += "location.replace('listAdmin?page=" + page + "');";
				html += "</script>";
				html += "</head>";
				html += "</html>";
				
				try {
					response.setCharacterEncoding("utf-8");
					PrintWriter out = response.getWriter();
					out.print(html);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				Util.getInstance().alertPage("관리자 계정삭제에 실패하였습니다.", response);
			}
			
		}
		
		return null;
	}
	
	/** 관리자 계정 조회 */
	@RequestMapping(value = "viewAdmin", method = RequestMethod.GET)
	public String viewAdmin(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		String idStr = request.getParameter("id");
		String pageStr = request.getParameter("page");
		
		if (idStr == null || idStr.equals("") || pageStr == null || pageStr.equals("")) {
			Util.getInstance().alertPage("필수입력 항목이 누락되었습니다.", response);
		} else {
			int id = Integer.parseInt(idStr);
			int page = Integer.parseInt(pageStr);
			
			AdminItem item = new AdminItem();
			item.setIdAdmin(id);
			
			AdminItem result = adminDao.getAdmin(item);
			model.addAttribute("item", result);
			model.addAttribute("page", page);
			
			HttpSession session = request.getSession();
			model.addAttribute("adminInfo", (AdminItem) session.getAttribute("ADMIN_INFO"));
		}
		
		return "admin/viewAdmin";
	}
	
	/** 관리자계정 수정후 리스트 목록 */
	@RequestMapping(value = "editAdminOk", method = RequestMethod.POST)
	public String editAdminOk(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
		
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		String nickName = request.getParameter("nickName");
		nickName = nickName.replace("&", "&amp;");
		nickName = nickName.replace("<", "&lt;");
		nickName = nickName.replace(">", "&gt;");
		String adminId = request.getParameter("adminId");
		String passWord1 = request.getParameter("passWord1");
		String adminLevelStr = request.getParameter("adminLevel");
		String idAdminStr = request.getParameter("idAdmin");
		String pageStr = request.getParameter("page");
		
		if (nickName == null || adminId == null || passWord1 == null || adminLevelStr == null || idAdminStr == null || pageStr == null ||
				nickName.equals("") || adminId.equals("") || passWord1.equals("") || adminLevelStr.equals("") || idAdminStr.equals("") ||
				pageStr.equals("")) {
			Util.getInstance().alertPage("필수입력 항목이 누락되었습니다.", response);
		} else {
			int adminLevel = Integer.parseInt(adminLevelStr);
			int idAdmin = Integer.parseInt(idAdminStr);
			AdminItem item = new AdminItem();
			item.setNickName(nickName);
			item.setAdminId(adminId);
			item.setAdminPw(passWord1);
			item.setAdminLevel(adminLevel);
			item.setIdAdmin(idAdmin);
			
			int page = Integer.parseInt(pageStr);
			
			int result = adminDao.editAdmin(item);
			
			if (result > 0) {
				try {
					response.sendRedirect("listAdmin?page=" + page);
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				Util.getInstance().alertPage("수정에 실패하였습니다.", response);
			}
		}
		return null;
	}
	
}
